﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Web;

namespace Step4.Unit9.Filters
{
    /// <summary>
    /// 自定义授权过滤器
    /// </summary>
    public class CustomerAuthorizeAttribute : Attribute,IAuthorizationFilter // 过滤器类名一定要以"Attribute"结尾，因为是以特性的方式使用的
    {
        public void OnAuthorization(AuthorizationFilterContext context) // AuthorizationFilterContext  授权过滤器上下文
        {
            // 获取用户要访问的"目标地址"
            var controller = context.RouteData.Values["controller"];
            var action = context.RouteData.Values["action"];

            // 判断用户是否登录了
            if (!context.HttpContext.User.Identity!.IsAuthenticated)
            {                                                                                       // 带有"/"的路由必须进行Url编码
                context.Result = new RedirectToActionResult("Login", "Account", new { redirectUrl = HttpUtility.UrlEncode($"/{controller}/{action}") });

            }
        }
    }
}
    